package routower

import (
	"time"
	"wzgames/internal/constant"
	"wzgames/pkg/common/timingwheel"
)

// 轮次倒计时播报

type CdRunner struct {
	core *RouManager

	cd          int64
	totalTime   int64 // 每轮投注时长 毫秒
	stopBetTime int64 // 停止投注时长 毫秒
	timeStep    int64 // 播报频率 毫秒
	roundId     int64

	interval time.Duration
	cdTimer  *timingwheel.Timer
}

func (am *CdRunner) Init(c *RouManager) error {
	am.core = c
	am.totalTime = 28000
	am.stopBetTime = 2000
	am.timeStep = 100
	am.interval = time.Duration(am.timeStep) * time.Millisecond

	return nil
}

func (am *CdRunner) Reset() {
	am.cd = am.totalTime
	if am.cdTimer != nil {
		am.cdTimer.Stop()
	}
}

func (am *CdRunner) Run(roundId int64) {
	am.roundId = roundId
	am.cdTimer = TimerAfter(am.interval, am.DoElapse, nil)
}

func (am *CdRunner) DoElapse(data interface{}) {
	am.cd -= am.timeStep
	am.core.PublishCurrentElapse(am.cd)
	if am.cd == am.stopBetTime {
		am.core.changeToState(constant.RouStopBetState)
	} else if am.cd > 0 {
		am.cdTimer = TimerAfter(am.interval, am.DoElapse, nil)
	} else {
		am.core.Open()
	}
}
